﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using CommClass;

namespace DMS
{
    public partial class FrmMergeView : DMS.FrmTemplate
    {
        MO mo = new MO(App.Ds);
        string sqlcmd = "";
        public FrmMergeView()
        {
            InitializeComponent();

            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = "yyyy-MM-dd HH:mm:ss";
        }
        int zhuangtai = 0;
        
        private void FrmMergeView_Load(object sender, EventArgs e)
        {
            //承运商下拉
            DataTable dt =mo.GetCarrierID();
            DataRow dr = dt.NewRow();
            dr["CarrierID"] = "0";
            dr["CarrierName"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            cmbcarrierid.DataSource = dt;
            cmbcarrierid.DisplayMember = "CarrierName";
            cmbcarrierid.ValueMember = "CarrierID";
            //默认选中
            cmbcarrierid.SelectedIndex = 0;



            string sqlcase;
            if (App.AppUser.CompanyID == 0)
            {
                sqlcase = "";
            }
            else
            {
                sqlcase = " and carrierid='" + App.AppUser.CompanyID + "'";
            }

            //获取车辆信息
            DataTable dtt = mo.GetVehicleInfo(sqlcase);
            DataRow drw = dtt.NewRow();
            drw["Vehicleid"] = "0";
            drw["VehicleNumber"] = "请选择";
            dtt.Rows.InsertAt(drw, 0);
            comboBox1.DataSource = dtt;
            comboBox1.DisplayMember = "VehicleNumber";
            comboBox1.ValueMember = "VehicleNumber";
            comboBox1.SelectedIndex = 0;

            cmbvehcount.SelectedIndex = 0;
         
        }


        
        
        //定义传递合并拣货单号
        private string semergenumber = null;
        public string SeMergeNumber
        {
            get
            {
                return semergenumber;
            }
        }
              
       
        private void button1_Click(object sender, EventArgs e)
        {
            string vehnumber = txbvehnumber.Text.Trim();
          
            string carrierid = cmbcarrierid.SelectedValue.ToString();
            string mergenumber = txbmergenumber.Text.Trim();
             sqlcmd = "";
            if (vehnumber != "")
            {
                sqlcmd = sqlcmd + " and d.vehiclenumber like '%" + vehnumber + "%'";
            }
            if (mergenumber != "")
            {
                sqlcmd = sqlcmd + " and m.mergenumber='" + mergenumber + "'";
            }
            if (Int32.Parse(carrierid) > 0)
            {
                sqlcmd = sqlcmd + " and c.carrierid='" + carrierid + "'";
            }
            if (chbsetted.Checked)
            {
                sqlcmd = sqlcmd + " and m.isprodsetted=0";
                zhuangtai = 0;
            }
            else
            {
                sqlcmd = sqlcmd + " and m.isprodsetted=1";
                zhuangtai = 1;
            }
            

            dgvmerge.DataSource =mo.GetMergeData1(sqlcmd);
            dgvmerge.Columns["拣货单号"].DefaultCellStyle.BackColor = Color.AliceBlue;
            dgvmerge.Columns["手工分配货位"].DefaultCellStyle.BackColor = Color.AliceBlue;
        }
              

      

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == -1 || e.RowIndex == -1) return;
            if (e.ColumnIndex == 1)
            {
                int row = dgvmerge.Rows[e.RowIndex].Index;
                semergenumber = dgvmerge.Rows[row].Cells[1].Value.ToString();//当前选定的合并拣货单号
                FrmMergeEdit form = new FrmMergeEdit();
                form.ReMergeNumber = semergenumber;
                form.ShowDialog();


                dgvmerge.DataSource = mo.GetMergeData1(sqlcmd);
            }
            if (e.ColumnIndex == 5)
            {

                if (zhuangtai == 1)
                {
                    MessageBox.Show("已集货,不能分配货位！");
                    return;
                }
                else
                {

                    int row = dgvmerge.Rows[e.RowIndex].Index;
                    semergenumber = dgvmerge.Rows[row].Cells[1].Value.ToString();//当前选定的合并拣货单号
                    FrmMergeEditupdate form1 = new FrmMergeEditupdate();
                    form1.ReMergeNumber = semergenumber;
                    form1.ShowDialog();


                    dgvmerge.DataSource = mo.GetMergeData1(sqlcmd);
                }

             
            }
        }

        private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            


        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (zhuangtai == 1)
            {
                MessageBox.Show("不能重复集货！");
                return;
            }
            DataGridView gv = dgvmerge;
            if (dgvmerge.RowCount > 0)
            {
            //string vehsite = cmbvehsite.SelectedValue.ToString();
            //string vehsite="0";
            using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
            {
                conn.Open();
                using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.Transaction = tran; //获取或设置将要其执行的事务  
                        try
                        {
                            for (int i = 0; i < gv.RowCount; i++)
                            {
                                if (gv.Rows[i].Cells[0].EditedFormattedValue.ToString() == "True")
                                {
                                    DataTable dtt22222222 = mo.Getjihuo11(" c.[MergeNumber] = '" + gv.Rows[i].Cells[1].Value.ToString() + "'", cmd);
                                    if (dtt22222222.Rows.Count > 0)
                                    {
                                        lbmergenumber.Items.Add("未分配完货位，不能集货！" + gv.Rows[i].Cells[1].Value.ToString());

                                    }
                                    else
                                    {

                                        //修改状态
                                        mo.UpdateMergeStatus111(gv.Rows[i].Cells[1].Value.ToString(), dateTimePicker1.Text.Trim(), conn, cmd);
                                        //修改车号车次
                                        if (comboBox1.SelectedIndex != 0 && cmbvehcount.SelectedIndex != 0)
                                        {
                                            string vehiclenum = comboBox1.SelectedValue.ToString();
                                            string vehorder = cmbvehcount.SelectedItem.ToString();
                                            mo.UpdateMergeStatus222(gv.Rows[i].Cells[1].Value.ToString(), vehiclenum, vehorder, conn, cmd);
                                        }

                                        lbmergenumber.Items.Add("已确认：" + gv.Rows[i].Cells[1].Value.ToString());
                                        //查询明细
                                        DataTable dtt111 = mo.GetDOEntrychuku(" [DOEntryID] in (select [DOEntryID] from [t_DOEntry] where [DeliveryNumber] in (select  [DONumber] from [t_MOEntry] where [MergeNumber] ='" + gv.Rows[i].Cells[1].Value.ToString() + "' and [IsDeleted] = " + App.notfreeze + ")) ", cmd);
                                        if (dtt111.Rows.Count > 0)
                                        {
                                            for (int j = 0; j < dtt111.Rows.Count; j++)
                                            {
                                                //修改库存
                                                mo.updateStork(" StockQty=StockQty-" + dtt111.Rows[j]["StockQty"].ToString(), dtt111.Rows[j]["StockTakingid"].ToString(), conn, cmd);

                                            }
                                            //删除空库存
                                            //  mo.deletStork(" StockQty=0 ", conn, cmd);

                                    }
                                    
                                    }
                                }
                            }
                            tran.Commit();
                            conn.Close();

                           // MessageBox.Show("集货成功！");
                        }
                        catch
                        {

                            tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                            conn.Close();
                              MessageBox.Show("集货失败！");
                        }
                    }
                }
            }
            
            dgvmerge.DataSource = mo.GetMergeData1(sqlcmd);
            }
        }

      

        private void button3_Click(object sender, EventArgs e)
        {
            if (zhuangtai == 1)
            {
                MessageBox.Show("已集货，不能分配货位！");
                return;
            }
            DataGridView gv = dgvmerge;
            if (dgvmerge.RowCount > 0)
            {
                 using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
            {
                conn.Open();
                using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.Transaction = tran; //获取或设置将要其执行的事务  
                        try
                        {
                            for (int i = 0; i < gv.RowCount; i++)
                            {
                               
                                if (gv.Rows[i].Cells[0].EditedFormattedValue.ToString() == "True")
                                {
                                    string messssss = "";
                                     DataTable dtt22222222 = mo.Getjihuo( " c.[MergeNumber] = '"+gv.Rows[i].Cells[1].Value.ToString()+"'", cmd);
                                     if (dtt22222222.Rows.Count == 0)
                                     {
                                         lbmergenumber.Items.Add("已分配完货位，请集货！" + gv.Rows[i].Cells[1].Value.ToString());
                                         messssss = "分配";
                                     }
                                     else
                                     {
                                        
                                         for (int j = 0; j < dtt22222222.Rows.Count; j++)
                                         {
                                             //查询库存
                                             StringBuilder sqlsb = new StringBuilder();
                                             sqlsb.Append(" [StockUseableQty] >0  ");
                                             sqlsb.Append(" and  [ProdID] =  " + dtt22222222.Rows[j]["ProdID"].ToString());
                                             sqlsb.Append(" and [StorageID] in (select [StorageID] from t_Storage where [freeze] =" + App.notfreeze + ")  and [StorageID] in ( select a.StorageID from  t_Storage a,t_Kuqu b where  a.[KuquID] = b.[KuquID] and b.[StoreID]= " + dtt22222222.Rows[j]["StoreID"].ToString() + "   )  and StockPinZhiID =" + App.newstatus);
                                             if (dtt22222222.Rows[j]["Batch"] != null && dtt22222222.Rows[j]["Batch"].ToString() != "")
                                             {
                                                 sqlsb.Append(" [Batch] =  '" + dtt22222222.Rows[j]["Batch"].ToString() + "' ");
                                             }
                                             DataTable dttstork = mo.GetStork(sqlsb.ToString(), " Batch,InputDate ", cmd);
                                             if (dttstork.Rows.Count == 0)
                                             {
                                                 if (dtt22222222.Rows[j]["chukukucunID"] == null || dtt22222222.Rows[j]["chukukucunID"].ToString() == "")
                                                 {
                                                     //插入出库明细,无货位，无批次
                                                     mo.insertchukukucun(dtt22222222.Rows[j]["DOEntryID"].ToString(), null, dtt22222222.Rows[j]["OrderQty"].ToString(), null, null, null, "0", conn, cmd);
                                                 }
                                             } else
                                             {
                                                 messssss = "分配";
                                                 double shuliang = double.Parse(dtt22222222.Rows[j]["OrderQty"].ToString());
                                                 if (dtt22222222.Rows[j]["StockQty"] != null && dtt22222222.Rows[j]["StockQty"].ToString() != "")
                                                 {
                                                      shuliang = double.Parse(dtt22222222.Rows[j]["StockQty"].ToString());
                                                 }
                                               
                                                 if (dtt22222222.Rows[j]["chukukucunID"] != null && dtt22222222.Rows[j]["chukukucunID"].ToString() != "")
                                                 {
                                                     mo.deletchukukucun(" chukukucunID =" + dtt22222222.Rows[j]["chukukucunID"].ToString(), conn, cmd);
                                                 }
                                                
                                                 for (int k = 0; k < dttstork.Rows.Count; k++)
                                                 {
                                                     double kucun = double.Parse(dttstork.Rows[k]["StockUseableQty"].ToString());
                                                     if (shuliang <= kucun)
                                                     {
                                                         //如果库存已经满足，跳出循环
                                                         mo.updateStork("StockUseableQty = " + (kucun - shuliang), dttstork.Rows[k]["StockTakingid"].ToString(), conn, cmd);
                                                         //插入出库明细
                                                         mo.insertchukukucun(dtt22222222.Rows[j]["DOEntryID"].ToString(), dttstork.Rows[k]["StorageID"].ToString(), Convert.ToString(shuliang), dttstork.Rows[k]["Batch"].ToString(), dttstork.Rows[k]["ProduceDate"].ToString(), dttstork.Rows[k]["StockPinZhiID"].ToString(), dttstork.Rows[k]["StockTakingid"].ToString(), conn, cmd);
                                                         break;
                                                     }
                                                     if (shuliang > kucun)
                                                     {
                                                         //如果库存没有满足，继续分配别的库存
                                                         mo.updateStork("StockUseableQty = " + 0, dttstork.Rows[k]["StockTakingid"].ToString(), conn, cmd);
                                                         //插入出库明细
                                                         mo.insertchukukucun(dtt22222222.Rows[j]["DOEntryID"].ToString(), dttstork.Rows[k]["StorageID"].ToString(), dttstork.Rows[k]["StockUseableQty"].ToString(), dttstork.Rows[k]["Batch"].ToString(), dttstork.Rows[k]["ProduceDate"].ToString(), dttstork.Rows[k]["StockPinZhiID"].ToString(), dttstork.Rows[k]["StockTakingid"].ToString(), conn, cmd);
                                                     }
                                                     if ((i + 1) == dttstork.Rows.Count && shuliang > kucun)
                                                     {
                                                         //插入出库明细,无货位，无批次
                                                         mo.insertchukukucun(dtt22222222.Rows[j]["DOEntryID"].ToString(), null, Convert.ToString(shuliang - kucun), null, null, null, "0", conn, cmd);
                                                     }
                                                     shuliang = shuliang - kucun;

                                                 }
                                                 
                                             }

                                         }
                                     }
                                     if (messssss == "")
                                     {
                                         lbmergenumber.Items.Add("无库存可分配！" + gv.Rows[i].Cells[1].Value.ToString());
                                     }
                                     else
                                     {
                                         lbmergenumber.Items.Add("继续分配货位完成！" + gv.Rows[i].Cells[1].Value.ToString());
                                     }
                                }
                                
                            }
                            tran.Commit();
                            conn.Close();

                            MessageBox.Show("集货成功！");
                        }
                        catch
                        {

                            tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                           conn.Close();
                            MessageBox.Show("继续分配失败！");
                        }
                    }
                }
            }

            }
        }

             

      
    }
}
